<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model="username" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model="age" min="0" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <!-- <button @click="addFn">添加/修改</button> -->
      <button @click="changeFn">添加/修改</button>
    </div>

    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in myArr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="delBtn(index)">删除</button>
            <button @click="editBtn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      username: "",
      age: "",
      sex: "男",
      myArr: [],
      myindex: "",
      current: 0,
    };
  },
  methods: {
    changeFn() {
      this.myArr.splice(
        this.current ? this.myindex : this.myArr.length,
        this.current,
        {
          name: this.username,
          age: this.age,
          sex: this.sex,
        }
      );
      this.username = "";
      this.age = "";
      this.current = 0;
    },
    delBtn(index) {
      this.myArr.splice(index, 1);
    },
    editBtn(index) {
      console.log(index);
      this.username = this.myArr[index].name;
      this.age = this.myArr[index].age;
      this.myindex = index;
      this.current = 1;
    },
  },
};
</script>